package cn.com.libertymutual.sys.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.com.libertymutual.core.exception.CustomJDBCException;
import cn.com.libertymutual.core.exception.CustomLangException;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sys.bean.SysMenu;
import cn.com.libertymutual.sys.bean.SysMenuRes;
import cn.com.libertymutual.sys.bean.SysRoleMenu;
import cn.com.libertymutual.sys.dao.ISysMenuDao;
import cn.com.libertymutual.sys.dao.ISysMenuResDao;
import cn.com.libertymutual.sys.dao.ISysRoleMenuDao;
import cn.com.libertymutual.sys.service.api.IInitSharedMemory;
import cn.com.libertymutual.sys.service.api.SysMenuService;
import cn.com.libertymutual.sys.vo.MenuConvert;
import cn.com.libertymutual.sys.vo.MenuInfoVO;

@Service("SysMenuService")
public class SysMenuServiceImpl implements SysMenuService {
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ISysMenuDao iSysMenuDao;
	@Resource RedisUtils redisUtils;
	@Autowired ISysMenuResDao  menuResDao;
	@Autowired
	private ISysRoleMenuDao iSysRoleMenuDao;
	@Autowired
	private IInitSharedMemory  initSharedMemory;
	@Override
	public ServiceResult findAll(boolean isLookup, String lookupDataOne,
			String lookupDataTwo, int pageNumber, int pageSize,
			String sortfield, String sorttype) {
		ServiceResult sr=new ServiceResult();
		Sort sort=null;
		if("ASC".equals(sorttype) ){
			sort =new Sort(Direction.ASC,sortfield);
		}else{
			sort =new Sort(Direction.DESC,sortfield);
		}
		
		if(isLookup){
			//设置查询条件 
			sr.setResult(iSysMenuDao.findAll(new Specification<SysMenu>(){  
				@Override
				public Predicate toPredicate(Root<SysMenu> root,
						CriteriaQuery<?> query, CriteriaBuilder cb) {			     			        
					List<Predicate> list = new ArrayList<>();
					list.add(cb.like(root.get("menuid").as(String.class),"%"+lookupDataOne+"%"));
					list.add(cb.like(root.get("menuname").as(String.class),"%"+lookupDataTwo+"%"));
					Predicate[] p = new Predicate[list.size()];
					
					
					return cb.and(list.toArray(p));
				}  
	        }, PageRequest.of(pageNumber - 1, pageSize, sort)));
		}else{
			sr.setResult(iSysMenuDao.findAll(PageRequest.of(pageNumber - 1, pageSize, sort)));
		}
		return sr;
	}

	@Override
	public ServiceResult saveSysMenu(SysMenu sysMenu) {
		ServiceResult sr = new ServiceResult();
		try{
			iSysMenuDao.save(sysMenu);
			sr.setSuccess();
		}catch(Exception e){
			sr.setFail();
			sr.setResult("操作失败，请稍后再试");
			log.error(e.getMessage(),e);
		}
		return sr;
	}

	@Override
	public ServiceResult updateSysMenu(SysRoleMenu sysRoleMenu) {
		ServiceResult sr=new ServiceResult();
		try{
			iSysRoleMenuDao.save(sysRoleMenu);
			iSysMenuDao.updateMenuStatus(sysRoleMenu.getMenuid(),Integer.parseInt(sysRoleMenu.getRoleid()));			
			sr.setSuccess();
		}catch(Exception e){
			sr.setFail();
			log.error(e.getMessage(),e);
		}
		return sr;
	}
	
	@Override
	public List<MenuInfoVO> getSysMenuInfo(Integer fmenuId ) throws CustomLangException  {
		List<MenuInfoVO> gg =null;
		try {
			Map<String, SysMenu> menuMap =  initSharedMemory.initSysMenu();
			
			Map<String, List<Integer>> menuMapRel = (Map<String, List<Integer>>)redisUtils.get( Constants.MENU_REL_INFO_KEY ) ;
			
			
			
			//UserInfo userInfo = (UserInfo)((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute(Constants.USER_INFO_KEY);
			//如果用户权限不为空,则查询菜单
				//String sql = "SELECT DISTINCT t1.menuid FROM tb_sys_role_menu t1 INNER JOIN tb_sys_menu t2 ON t1.menuid=t2.menuid WHERE t1.roleid IN ("+in_sql+") GROUP BY t1.menuid ORDER BY t2.orderid";
				List<Integer> menuIdList  =Lists.newArrayList();
				Iterator<String> mi = menuMap.keySet().iterator();
				while(mi.hasNext() ){
					
					menuIdList.add(Integer.parseInt(mi.next())); 
				}
	
				MenuConvert mc = new MenuConvert();
				
				//String sidsql = "select DISTINCT MENUID , RESID from tb_sys_role_menu_res where roleId in ("+in_sql+") order by menuId";
				Map<Integer,List<String>> mResIdList = Maps.newHashMap(); 
				List<SysMenuRes>  ress =menuResDao.findAll(); 
				for(SysMenuRes r : ress){
					Integer  menuId =	r.getMenuid();
					if(mResIdList.containsKey(menuId)){
						List<String> itemIdList = mResIdList.get(menuId);
						itemIdList.add(r.getResid());
					}else{
						List<String> itemIdList = Lists.newArrayList();
						itemIdList.add(r.getResid());
						mResIdList.put(menuId, itemIdList);
					}
				}
				//Map<Integer,List<String>> mResIdList = mc.convertResList( menuDao.nativeQuery4Map(sidsql) ); 
				gg = mc.genMenuTree(menuMap, menuIdList, menuMapRel, mResIdList, fmenuId) ;
		}catch(HibernateException e){
			log.error(e.getMessage(),e);
			throw new CustomJDBCException(e);
		}catch(Exception e){
			log.error(e.getMessage(),e);
			//将捕获到的异常转换为自定义异常抛出
			throw new CustomLangException(e);
		}
		return gg;
	}
	

}
